﻿using System.Data;
using Chaotic.DataBase.DataAccess;
using Chaotic.DataBase.DBAccessLibrary.DBAccessLibrary;
using Chaotic.DataBase.DBAccessLibrary.Interface;
using Chaotic.DataBase.DBAccessLibrary.Model;

namespace Chaotic.DataBase.MySQLAccess
{
    public class MysqlGrammar : DBGrammar, IGrammar, ILocalGrammar
    { 
        public MysqlGrammar(ConnectionModel? connect)
            : base(connect)
        {
        }

        public string? IsExistChTableSql
        {
            get
            {
                string? result = string.Empty;
                if (string.IsNullOrEmpty(_xml.ChDescription))
                {
                    result = "select name from INFORMATION_SCHEMA.TABLES where name='T_FIELD_DICTIONARY'";
                }
                return result;
            }
        }
 
        public string GetPageingSql(string sql, decimal index, decimal count)
        {
            string format = "SELECT tab.* FROM (SELECT {0} ROWNUMBER,t.* FROM (" + Environment.NewLine + "{1}" + Environment.NewLine + ") t) tab  WHERE tab.ROWNUMBER >= " + index + " and tab.ROWNUMBER < " + count;
            int length = sql.IndexOf("FROM", StringComparison.CurrentCultureIgnoreCase);
            string text = sql.Substring(0, length);
            if (text.IndexOf("count(") > 0 || text.IndexOf("sum(") > 0)
            {
                return sql;
            }
            if (sql.IndexOf("ORDER BY", StringComparison.CurrentCultureIgnoreCase) > 0)
            {
                sql = sql.Trim();
                if (sql.Substring(0, 6).ToLower() == "select" && !sql.Substring(6).Trim().StartsWith("TOP "))
                {
                    sql = sql.Insert(6, " TOP " + count + " ");
                }
            }
            return string.Format(format, "ROW_NUMBER() OVER(ORDER BY GETDATE())", sql);
        }
 
        public DatabaseType GetConnectionStr(out string connectStr)
        { 
            // 允许用户变量  命令超时
            connectStr = "Server={3};Database={0};Uid={1};Pwd={2};Allow User Variables=True;"; 
            connectStr = string.Format(connectStr, _connect.DataBase, _connect.UserID, _connect.PassWord, _connect.Server);
            return DatabaseType.Mysql;
        }
    }
}